package com.ruoyi.receipt.utils;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.utils.HttpClientUtils.doGetPost;

@Component
public class WeiXinMsg {

    @Autowired
    private RedisCache redisCache;

    private static RedisCache staticRedisCache;

    public static String appId;

    public static String appsecret;

    @PostConstruct
    public void init() {
        staticRedisCache = redisCache;
    }

    @Value("${weixin.appId}")
    public void setAppId(String appIds) {
        appId = appIds;
    }

    @Value("${weixin.appsecret}")
    public void setAppsecret(String appsecrets) {
        appsecret = appsecrets;
    }

    /**
     * 获取token
     * @return token
     */
    public String getToken(){

        String redisAccessToken = staticRedisCache.getCacheObject("weixin:accessToken");
        if(StringUtils.isNotEmpty(redisAccessToken)){
            return redisAccessToken;
        }

        //授予形式
        String grant_type = "client_credential";
        //接口地址拼接参数
        String getTokenApi = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+appId+"&secret="+appsecret;

        String tokenJsonStr =  doGetPost(getTokenApi,"GET",null);
        JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
        String accessToken = tokenJson.get("access_token").toString();

        staticRedisCache.setCacheObject("weixin:accessToken",accessToken,2, TimeUnit.HOURS);

        return accessToken;
    }


    /***
     * 发送消息
     * @param
     */
    public void sendMag(Map<String, Object> dataMap,String serviceId,String toUserOpenId){

        String token=getToken();

        //接口地址
        String sendMsgApi = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;

        //消息模板ID
        String template_id = "X8RC8_07_HcrhFvZ-R63x9MZ9iSerGvq52FMfOQ-7SQ";

        //点击访问地址
        String toUrl = "http://www.baidu.com?serviceId="+serviceId;

        //整体参数map
        Map<String, Object> paramMap = new HashMap<String, Object>();
        //点击消息跳转相关参数map
        Map<String, String> miniprogramMap = new HashMap<String, String>();
        //消息主题显示相关map

        paramMap.put("touser", toUserOpenId);
        paramMap.put("template_id", template_id);
        paramMap.put("url", toUrl);
        paramMap.put("miniprogram", miniprogramMap);
        paramMap.put("data", dataMap);

        doGetPost(sendMsgApi,"POST",paramMap);

    }


}
